//
//  YFWeiboOAuthViewController.swift
//  YFSwiftWeibo
//
//  Created by tsaievan on 2017/8/30.
//  Copyright © 2017年 tsaievan. All rights reserved.
//

import UIKit
import WebKit
import SVProgressHUD

class YFWeiboOAuthViewController: UIViewController {
    
    lazy var webView = WKWebView()
    
    lazy var progressView = UIProgressView(frame: CGRect(x: 0, y: 64, width: UIScreen.hm_screenWidth(), height: 0))
    
    override func loadView() {
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        loadRequest()
        webView.navigationDelegate = self
    }
    
    ///< 销毁通知
    deinit {
        webView.removeObserver(self, forKeyPath: "estimatedProgress")
    }
    
    @objc fileprivate func close() {
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
    }
    
    @objc fileprivate func autoFill() {
        let js = "document.getElementById('userId').value = 'caiyifancool333@sina.com';document.getElementById('passwd').value = '1292086774';"
        webView.evaluateJavaScript(js, completionHandler: nil)
    }
}

extension YFWeiboOAuthViewController {
    
    /// 设置UI
    fileprivate func setupUI() {
        webView.backgroundColor = UIColor.white
        webView.scrollView.isScrollEnabled = false
        progressView.tintColor = UIColor.orange
        webView.addSubview(progressView)
        addObservers()
        title = "登录新浪微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: #selector(close), isBack: true)
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFill), isBack: false)
    }
    
    /// 添加通知
    fileprivate func addObservers() {
        webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
    }
    
    /// 加载登录页面
    fileprivate func loadRequest() {
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(YFWeiboAppKey)&redirect_uri=\(YFRedirectURI)"
        guard let url = URL(string: urlStr) else {
            return
        }
        let request = URLRequest(url: url)
        webView.load(request)
    }
}

//MARK: -KVO监听回调
extension YFWeiboOAuthViewController {
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "estimatedProgress" {
            progressView.progress = Float(webView.estimatedProgress)
            progressView.isHidden = webView.estimatedProgress >= 1
        }
    }
}

//MARK: - UIWebViewDelegate

extension YFWeiboOAuthViewController: WKNavigationDelegate {
    
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        let url = webView.url
        // 如果不包含回调地址, 那么就加载网页
        if url?.absoluteString.hasPrefix(YFRedirectURI) == false {
            decisionHandler(.allow)
            return
        }
        // 如果不包含"code=", 那么就直接返回
        if url?.query?.hasPrefix("code=") == false {
            close()
            decisionHandler(.cancel)
            return
        }
        ///< 代码走到这里表示一定有查询字符串, 且包含"code="
        let code = url?.query?.substring(from: "code=".endIndex) ?? ""
        print("授权码 - \(code)")
        YFNetworkManager.shared.loadAccessToken(code: code) { (isSuccess) in
            if !isSuccess {
                SVProgressHUD.showInfo(withStatus: "登录失败")
            }else {
                SVProgressHUD.showInfo(withStatus: "登录成功")
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: YFWeiBoUserLoginSuccessNotification), object: nil)
                ///< 傻逼了, 这一步不能忘记, 要把这个控制器给dismiss掉
                self.close()
            }
        }
        decisionHandler(.cancel)
    }
    
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        SVProgressHUD.show()
    }

    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        SVProgressHUD.dismiss()
    }
}

